package com.indi.gulimall.ware.listener;

import com.indi.common.constant.WareConstant;
import com.indi.common.dto.OrderDTO;
import com.indi.common.dto.mq.StockLockDTO;
import com.indi.common.exception.BusinessException;
import com.indi.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author UnityAlvin
 * @date 2021/7/23 18:01
 */
@Service
@RabbitListener(queues = WareConstant.STOCK_RELEASE_STOCK_QUEUE)
public class StockReleaseListener {
    @Resource
    private WareSkuService wareSkuService;

    /**
     * 监听自动解锁
     *
     * @param stockLockDTO
     */
    @RabbitHandler
    public void handleStockLockRelease(StockLockDTO stockLockDTO, Message message, Channel channel) throws IOException {
        System.out.println("收到自动解锁库存的消息");

        try {
            wareSkuService.unlockStock(stockLockDTO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (BusinessException e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    /**
     * 监听主动解锁库存的消息
     *
     * @param orderDTO
     */
    @RabbitHandler
    public void handleUnlock(OrderDTO orderDTO, Message message, Channel channel) throws IOException {
        System.out.println("收到主动解锁库存的消息");

        try {
            wareSkuService.unlockStock(orderDTO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (BusinessException e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
